/** 
 * Copyright (C) 2018 Jeebiz (http://jeebiz.net).
 * All Rights Reserved. 
 */
package net.jeebiz.cloud.authz.feature.web.mvc;

import java.util.List;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.google.common.collect.Lists;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import net.jeebiz.cloud.api.ApiRestResponse;
import net.jeebiz.cloud.api.annotation.BusinessLog;
import net.jeebiz.cloud.api.annotation.BusinessType;
import net.jeebiz.cloud.api.webmvc.BaseApiController;
import net.jeebiz.cloud.authz.feature.dao.entities.AuthzFeatureModel;
import net.jeebiz.cloud.authz.feature.dao.entities.AuthzFeatureOptModel;
import net.jeebiz.cloud.authz.feature.service.IAuthzFeatureOptService;
import net.jeebiz.cloud.authz.feature.service.IAuthzFeatureService;
import net.jeebiz.cloud.authz.feature.setup.Constants;
import net.jeebiz.cloud.authz.feature.setup.handler.FeatureDataHandlerFactory;
import net.jeebiz.cloud.authz.feature.web.vo.AuthzFeatureNewVo;
import net.jeebiz.cloud.authz.feature.web.vo.AuthzFeatureRenewVo;
import net.jeebiz.cloud.authz.feature.web.vo.AuthzFeatureVo;

@Api(tags = "功能菜单：数据维护（Ok）")
@RestController
@RequestMapping(value = "/authz/feature/")
public class AuthzFeatureController extends BaseApiController {

	@Autowired
	protected IAuthzFeatureService authzFeatureService;
	@Autowired
	protected IAuthzFeatureOptService authzFeatureOptService;
	
	@ApiOperation(value = "功能菜单（全部数据）", notes = "查询功能菜单列表")
	@BusinessLog(module = Constants.AUTHZ_FEATURE, business = Constants.Biz.AUTHZ_FEATURE_TREE, opt = BusinessType.SELECT)
	@GetMapping("list")
	@PreAuthorize("authenticated")
	@ResponseBody
	public ApiRestResponse<List<AuthzFeatureVo>> list(){
		// 所有的功能菜单
		List<AuthzFeatureModel> featureList = getAuthzFeatureService().getFeatureList();
		List<AuthzFeatureVo> featureVoList = Lists.newArrayList();
		for (AuthzFeatureModel model : featureList) {
			featureVoList.add(getBeanMapper().map(model, AuthzFeatureVo.class));
		}
		return ApiRestResponse.success(featureVoList);
	}
	
	@ApiOperation(value = "功能菜单-树形结构数据（全部数据）", notes = "查询功能菜单树形结构数据")
	@BusinessLog(module = Constants.AUTHZ_FEATURE, business = Constants.Biz.AUTHZ_FEATURE_TREE, opt = BusinessType.SELECT)
	@GetMapping("tree")
	@PreAuthorize("authenticated")
	@ResponseBody
	public ApiRestResponse<List<AuthzFeatureVo>> tree(){
		// 所有的功能菜单
		List<AuthzFeatureModel> featureList = getAuthzFeatureService().getFeatureList();
		// 所有的功能操作按钮
		List<AuthzFeatureOptModel> featureOptList = getAuthzFeatureOptService().getFeatureOpts();
		// 返回各级菜单 + 对应的功能权限数据
		return ApiRestResponse.success(FeatureDataHandlerFactory.getTreeHandler().handle(featureList, featureOptList));
	}
	
	@ApiOperation(value = "功能菜单-扁平结构数据（全部数据）", notes = "查询功能菜单扁平结构数据")
	@BusinessLog(module = Constants.AUTHZ_FEATURE, business = Constants.Biz.AUTHZ_FEATURE_FLAT, opt = BusinessType.SELECT)
	@GetMapping("flat")
	@PreAuthorize("authenticated")
	@ResponseBody
	public ApiRestResponse<List<AuthzFeatureVo>> flat(){
		// 所有的功能菜单
		List<AuthzFeatureModel> featureList = getAuthzFeatureService().getFeatureList();
		// 所有的功能操作按钮
		List<AuthzFeatureOptModel> featureOptList = getAuthzFeatureOptService().getFeatureOpts();
		
		// 返回叶子节点菜单 + 对应的功能权限数据
		return ApiRestResponse.success(FeatureDataHandlerFactory.getFlatHandler().handle(featureList, featureOptList));
	}
	
	@ApiOperation(value = "增加功能菜单信息", notes = "增加功能菜单信息")
	@ApiImplicitParams({ 
		@ApiImplicitParam(paramType = "body", name = "featureVo", value = "功能菜单信息", dataType = "AuthzFeatureNewVo")
	})
	@BusinessLog(module = Constants.AUTHZ_FEATURE, business = Constants.Biz.AUTHZ_FEATURE_NEW, opt = BusinessType.INSERT)
	@PostMapping("new")
	@PreAuthorize("authenticated and (hasAuthority('feature:new') or hasAuthority('*')) ")
	@ResponseBody
	public ApiRestResponse<String> feature(@Valid @RequestBody AuthzFeatureNewVo featureVo) throws Exception { 
		
		int count = getAuthzFeatureService().getCountByCode(featureVo.getCode(), null);
		if(count > 0) {
			return fail("feature.new.code-exists");
		}
		AuthzFeatureModel model = getBeanMapper().map(featureVo, AuthzFeatureModel.class);
		/**
		 * 菜单类型(1:原生|2:自定义)
		 */
		model.setType("2");
		int total = getAuthzFeatureService().insert(model);
		if(total > 0) {
			return success("feature.new.success", total);
		}
		return fail("feature.new.fail", total);
	}
	
	@ApiOperation(value = "修改功能菜单信息", notes = "修改功能菜单信息")
	@ApiImplicitParams({ 
		@ApiImplicitParam(paramType = "body", name = "featureVo", value = "功能菜单信息", dataType = "AuthzFeatureRenewVo")
	})
	@BusinessLog(module = Constants.AUTHZ_FEATURE, business = Constants.Biz.AUTHZ_FEATURE_RENEW, opt = BusinessType.UPDATE)
	@PostMapping("renew")
	@PreAuthorize("authenticated and (hasAuthority('feature:renew') or hasAuthority('*')) ")
	@ResponseBody
	public ApiRestResponse<String> renew(@Valid @RequestBody AuthzFeatureRenewVo featureVo) throws Exception { 
		AuthzFeatureModel model = getBeanMapper().map(featureVo, AuthzFeatureModel.class);
		int total = getAuthzFeatureService().update(model);
		if(total > 0) {
			return success("feature.renew.success", total);
		}
		return fail("feature.renew.fail", total);
	}
	
	@ApiOperation(value = "查询功能菜单信息", notes = "根据功能菜单ID查询功能菜单信息")
	@ApiImplicitParams({ 
		@ApiImplicitParam( paramType = "path", name = "id", required = true, value = "功能菜单ID", dataType = "String")
	})
	@BusinessLog(module = Constants.AUTHZ_FEATURE, business = Constants.Biz.AUTHZ_FEATURE_DETAIL, opt = BusinessType.SELECT)
	@PostMapping("detail/{id}")
	@PreAuthorize("authenticated and (hasAuthority('feature:detail') or hasAuthority('*')) ")
	@ResponseBody
	public ApiRestResponse<AuthzFeatureVo> detail(@PathVariable("id") String id) throws Exception {
		AuthzFeatureModel model = getAuthzFeatureService().getModel(id);
		if( model == null) {
			return ApiRestResponse.empty(getMessage("feature.get.empty"));
		}
		return ApiRestResponse.success(getBeanMapper().map(model, AuthzFeatureVo.class));
	}
	
	@ApiOperation(value = "删除功能菜单信息", notes = "删除功能菜单信息")
	@ApiImplicitParams({ 
		@ApiImplicitParam( paramType = "path", name = "id", required = true, value = "功能菜单ID", dataType = "String")
	})
	@BusinessLog(module = Constants.AUTHZ_FEATURE, business = Constants.Biz.AUTHZ_FEATURE_DELETE, opt = BusinessType.DELETE)
	@PostMapping("delete/{id}")
	@PreAuthorize("authenticated and (hasAuthority('feature:delete') or hasAuthority('*')) ")
	@ResponseBody
	public ApiRestResponse<String> delFeature(@PathVariable String id) throws Exception {
		int count = getAuthzFeatureService().getCountByParent(id);
		if(count > 0) {
			return fail("feature.delete.child-exists");
		}
		int total = getAuthzFeatureService().delete(id);
		if(total > 0) {
			return success("feature.delete.success", total);
		}
		return success("feature.delete.fail", total);
	}
	
	public IAuthzFeatureService getAuthzFeatureService() {
		return authzFeatureService;
	}

	public void setAuthzFeatureService(IAuthzFeatureService authzFeatureService) {
		this.authzFeatureService = authzFeatureService;
	}

	public IAuthzFeatureOptService getAuthzFeatureOptService() {
		return authzFeatureOptService;
	}

	public void setAuthzFeatureOptService(IAuthzFeatureOptService authzFeatureOptService) {
		this.authzFeatureOptService = authzFeatureOptService;
	}
	
}
